package com.hcx.poi.xssf.eventmodel.sheethandler;

import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import com.hcx.excel.xlsx.Cell;
import com.hcx.poi.xssf.eventmodel.XSSFHelper;
import com.hcx.xml.sax.ElementContentHandler;

/**
 * 处理 Sheet#.xml 中的 /worksheet/sheetData/row/c 元素
 * 
 * @author 韩朝祥
 *
 */
public class SheetCellContentHandler implements ElementContentHandler {
	private SheetRowContentHandler rowContentHandler;
	private SharedStringsTable sst;
	private String cellType;
	private Cell cell;
	private int columnIndex;

	public SheetCellContentHandler(SheetRowContentHandler rowContentHandler,SharedStringsTable sst){
		this.rowContentHandler = rowContentHandler;
		this.sst = sst;
	}
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes atts) throws SAXException {
		cell = new Cell();
		cellType = atts.getValue("t");
		String cellPos = atts.getValue("r");
		columnIndex = XSSFHelper.getColumnIndex(cellPos);
	}

	@Override
	public void endElement(String uri, String localName, String qName,
			String content) throws SAXException {
		rowContentHandler.addCell(cell, columnIndex);
		cell = null;
	}

	@Override
	public boolean isTextElement() {
		return false;
	}

	@Override
	public String getHandlePath() {
		return "/worksheet/sheetData/row/c";
	}

	void setCellValue(String value) {
		if ("s".equals(cellType)) {
			String v = new XSSFRichTextString(sst.getEntryAt(Integer
					.parseInt(value))).toString();
			cell.setValue(v);
		} else {
			cell.setValue(value);
		}
	}
}
